"use client";
import { useRef, useEffect } from "react";
import { Button } from "@/components/ui/button";
import { config } from "@/config";
import { useSSE } from "@/hooks/sse-connector";
import { TestDataGenerator } from "@/lib/utils";
import { Inbox, Terminal } from "lucide-react";
import OutLoopFlow from "@/components/outloop/outloop-flow";
import { ReactFlowProvider } from "@xyflow/react";

export default function Page() {
  const { messages, connect, sseData } = useSSE();
  // 日志自动滚动到底部
  const logRef = useRef<HTMLDivElement>(null);

  useEffect(() => {
    if (logRef.current) {
      logRef.current.scrollTop = logRef.current.scrollHeight;
    }
  }, [messages]);

  const handleStart = () => {
    connect(
      `${config.AI_SERVICE_URL}${config.AI_SERVICE_URL_PREFIX}/rl_outer_running`,
      {
        generator: TestDataGenerator,
      }
    );
  };

  return (
    <div className="my-2 flex-1 rounded-md flex flex-col gap-2 p-4">
      <div className="text-sm font-medium flex gap-2">
        <Terminal className="h-5 w-5" />
        <span>训练日志</span>
      </div>
      <div
        ref={logRef}
        className="bg-neutral-900/95 rounded-md p-4 h-60 overflow-y-auto border font-mono text-xs text-green-400"
      >
        {messages.length === 0 && "训练未开始"}
        {messages.map((log: string, index: number) => (
          <div key={index} className="mb-1 whitespace-pre-wrap break-all">
            <span className="text-green-600">$</span> {log}
          </div>
        ))}
      </div>
      <div className="flex-1">
        {sseData.length === 0 ? (
          <div className="flex flex-col items-center justify-center h-full text-muted-foreground">
            <Inbox className="w-16 h-16 mb-4" />
            <p className="text-lg font-medium">暂无训练数据</p>
            <p className="text-sm">开始训练以查看可视化结果。</p>
          </div>
        ) : (
          <ReactFlowProvider>
            <OutLoopFlow
              inputImageUrl={(sseData.at(-1)?.inputImages as string[])[0]}
              outputImageUrl={(sseData.at(-1)?.outputImages as string[])[0]}
              chosenModels={sseData.at(-1)?.chosenModel as string[]}
            />
          </ReactFlowProvider>
        )}
      </div>
      <div>
        <Button onClick={handleStart}>训练开始</Button>
      </div>
    </div>
  );
}
